from decimal import Decimal

import boto3
from botocore.exceptions import ClientError


def create_table(dynamodb=None):
    if not dynamodb:
        # dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")
        # "https://sqs.us-east-2.amazonaws.com/599885534814/%s"
        dynamodb = boto3.resource('dynamodb')

    table = dynamodb.create_table(
        TableName='SpiderMonitor',
        KeySchema=[
            {
                'AttributeName': 'JobId',
                'KeyType': 'HASH'  # Partition key
            },
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'JobId',
                'AttributeType': 'S'
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 10,
            'WriteCapacityUnits': 10
        }
    )
    return table


def put_item(title, year, plot):
    dynamodb = boto3.resource('dynamodb')

    table = dynamodb.Table('SpiderMonitor')
    response = table.put_item(
        Item={
            'JobId': '2021-08-23',
            'Info': {"Type": "CoreProduct", "SubType": ["BestWishes", "BestSeller"]}
        }
    )
    return response


def get_movie(title, year):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Movies')

    response = table.get_item({})
    print(response['Item'])


def update_movie(rating, plot, actors):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('SpiderProcessQueue')

    response = table.update_item(
        Key={
            'jobId': '2021-09-03'
        },
        UpdateExpression="set info.rating=:r, info.plot=:p, info.actors=:a",
        ExpressionAttributeValues={
            ':r': Decimal(rating),
            ':p': plot,
            ':a': actors
        },
        ReturnValues="UPDATED_NEW"
    )
    return response


def delete_underrated_job(jobId):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('SpiderMonitor')

    try:
        response = table.delete_item(
            Key={
                'JobId': jobId
            },
            # ConditionExpression="info.rating <= :val",
            # ExpressionAttributeValues={
            #     ":val": Decimal(rating)
            # }
        )
    except ClientError as e:
        if e.response['Error']['Code'] == "ConditionalCheckFailedException":
            print(e.response['Error']['Message'])
        else:
            raise
    else:
        return response


def delete_table():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('SpiderMonitor')
    table.delete()


if __name__ == '__main__':
    # movie_table = create_table()
    # print("Table status:", movie_table.table_status)

    put_item("", "", "")

    # get_movie("", "")

    # update_response = update_movie(
    #     "The Big New Movie", 2015, 5.5, "Everything happens all at once.",
    #     ["Larry", "Moe", "Curly"])

    # delete_response = delete_underrated_job("2021-08-23")

    # delete_table()
